<template>
  <el-form class="" :model="passage" label-width="100px">
    <el-form-item label="新闻标题">
      <el-input v-model="passage.title"></el-input>
    </el-form-item>
    <!-- <QuillEditor
      v-model:content="passage.content"
      :options="editorOption"
      contentType="html"
      theme="snow"
    /> -->
    <el-form-item label="新闻内容" prop="content">
      <el-input
        v-model="passage.content"
        style="width: 700px"
        :autosize="{ minRows: 4, maxRows: 6 }"
        type="textarea"
        placeholder="请输入新闻内容"
      />
    </el-form-item>
    <el-form-item>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="'/api/files/uploadImg?relativePath=' + relativePath"
        :auto-upload="false"
        :on-change="handleChange"
        :file-list="fileList"
        :on-remove="beforeRemove"
      >
        <el-button type="primary" size="small">选取文件</el-button>
        <template #tip>
          <div class="el-upload__tip">选择要上传的图片，且不超过1M</div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-switch
        v-model="isCarousel"
        active-text="设为轮播图"
        @change="changeFileType"
      ></el-switch>
    </el-form-item>

    <el-form-item label="新闻类型" prop="passageTypeId">
      <el-select v-model="passage.passageTypeId" placeholder="请选择新闻类型">
        <el-option
          v-for="newsType in newsTypeList"
          :key="newsType.id"
          :label="newsType.type"
          :value="newsType.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="add">添加</el-button>
      <el-button @click="goBack">返回</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

const OK = 200;
const router = useRouter();
const route = useRoute();
const uploadRef = ref(null);

const passage = ref({});
const passageId = ref(0);
const newsTypeList = ref([]);
const editorOption = ref({
  placeholder: "输入新闻内容：",
  theme: "snow",
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ header: 1 }, { header: 2 }],
      [{ list: "ordered" }, { list: "bullet" }],
      [{ script: "sub" }, { script: "super" }],
      [{ indent: "-1" }, { indent: "+1" }],
      [{ direction: "rtl" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ["clean"],
      ["link", "image"],
    ],
  },
});
const imageUrl = ref("");
const fileList = ref([]);
const file = ref({});
const isCarousel = ref(false);
const relativePath = ref("/images/passage/");

const add = () => {
  addNews();
};

const addNews = async () => {
  try {
    const res = await axios.post("/api/passages", passage.value);
    if (res.data.code === OK) {
      passageId.value = res.data.data;
      file.value.passageId = passageId.value;
      uploadRef.value.submit();

      setTimeout(() => {
        ElMessage.success("添加新闻成功");
      }, 800);

      setTimeout(() => {
        router.push({ name: "PassageList" });
      }, 1500);
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("添加新闻失败");
  }
};

const saveFile = async () => {
  const res = await axios.post("/api/files/passage", file.value);
  if (res.data.code === OK) {
    ElMessage.success("上传文件成功");
  } else {
    ElMessage.error(res.data.message);
  }
};

const getNewsTypeList = async () => {
  try {
    const res = await axios.get("/api/passageTypes");
    if (res.data.code === OK) {
      newsTypeList.value = res.data.data;
    } else {
      ElMessage.error(res.data.data);
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("获取新闻类型列表失败");
  }
};

const handleChange = (file1, fileList) => {
  const response = file1.response;
  if (response && response.code === OK) {
    file.value.filePath = response.data;
    file.value.fileName = getFileName(file.value.filePath);
    file.value.passageId = passageId.value;
    console.log(file.value, "file.value----------------");
    ElMessage.success("上传文件成功");
    saveFile();
  }
  fileList.value = fileList.slice(-3);
};

const getFileName = (filePath) => {
  let fileName = null;
  if (filePath) {
    if (filePath.includes("/")) {
      fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
    }
  }
  return fileName;
};

const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`);
};

const changeFileType = () => {
  if (isCarousel.value) {
    file.value.fileTypeId = 4;
  } else {
    file.value.fileTypeId = 5;
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  getNewsTypeList();
});

watch(
  () => route.path,
  () => {
    getNewsTypeList();
  }
);
</script>

<style scoped>
</style>
